var $content;

function loadEvents(){
	$.mobile.showPageLoadingMsg();
	
	$content = $(".page-events div:jqmData(role=content)");
	$content.html("");

	$.ajax ({
		dataType: "json",
		url : "http://vlove.helia-agency.com/event/views/liste_events",
		success: function(result){
			console.log(result);

			showEvents(result);
		},
		error : function (error){
			console.log(error);
		}
	});

}

function showEvents(events){
	var html = '<ul id="events" data-role="listview" data-filter-placeholder="Rechercher une actualité ..." data-filter="true" data-icon="arrow-r" data-iconpos="right">';

	$.each(events, function(key, ev) {
		console.log(ev);
		html += '<li> <a href="#" id="' + ev.nid + '"> <h2>' + ev.title + '</h2><img src="http://vlove.helia-agency.com/sites/default/files/styles/thumbnail/public/evenement/' + ev.field_image.und[0]['filename'] + '" /><span class="date">' + ev.field_date.und[0]['value'] + '</span> <p class="accroche"><strong>' + ev.field_accroche.und[0]['value'] + '</strong></p></a> </li>';
	});

	html += '</ul>';

	$content.prepend(html);

	$("#events").listview();

	addClickEvent();
	$.mobile.hidePageLoadingMsg();
}

function addClickEvent(){
	$("#events li a").click(function(e){
		e.preventDefault();

		var targetID = $(this).attr('id');

		$.mobile.changePage( "event.html", {
			data : {'nid':targetID},
			transition : 'fade'
		});
	})
}

$(".page-events").on("pageshow", function (event) {
	$('.menu').load('menu.html',function(){ $('#menu').panel(); });
	
	loadEvents();
});